package com.tengju.bff.interfaces.covercharge.util.alarmUtil;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.idanchuang.component.base.JsonResult;
import com.tengju.bff.interfaces.shared.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.helpers.MessageFormatter;

import java.util.Date;

/**
 * MsgSendUtil
 * <p>
 * 消息发送
 *
 * @author: Giles
 * @date: 2018/1/13 17:32
 */
@Slf4j
public class MsgSendUtil {

    /**
     * 消息类型
     */
    public static class MsgType {
        public static final String DINGDING = "d";
        public static final String MAIL = "m";
    }

    private static final Logger LOG = LoggerFactory.getLogger(MsgSendUtil.class);

    private static final String MSG_LINE = "\n";
    private static final String HTML_LINE = "<br>";
    private static String LINE_SEPARATOR;

    private MsgSendUtil() {
        getLineSeparator();
    }

    /**
     * 警告消息发送
     *
     * @param title
     * @param msg
     * @return
     */
    public static boolean sendWarnMsg(String title, String msg) {
        String mdcId = MDCUtils.get();
        try {
            MsgSendConfig.getInstance().getPoolTaskExecutor().execute(() -> {
                MDCUtils.put(mdcId);
                DingUtils.groupNotice(title + "\r\n" + buildMsg(msg, true).toString(), null);
            });
            return true;
        } catch (Exception e) {
            LOG.error("sendWarnMsg error:{}", e.getMessage());
            return false;
        }
    }

//    public static boolean sendDingMsg(String format, Object... objs) {
//        String mdcId = MDCUtils.get();
//        try {
//            MsgSendConfig.getInstance().getPoolTaskExecutor().execute(() -> {
//                MDCUtils.put(mdcId);
//                DingUtils.groupNotice(MessageFormatter.arrayFormat(format, objs).getMessage(), null);
//            });
//            return true;
//        } catch (Exception e) {
//            LOG.error("sendWarnMsg error:{}", e.getMessage());
//            return false;
//        }
//    }


    public static boolean sendLarkMsg(String format, Object... objs) {
        try {
            LarkSendHelper.getInstance().sendMsg(MessageFormatter.arrayFormat(format, objs).getMessage());
            return true;
        } catch (Exception e) {
            LOG.error("sendWarnMsg error:{}", e.getMessage());
            return false;
        }
    }


    /**
     * 未知异常消息发送
     *
     * @param title
     * @param msg
     * @return
     */
    public static boolean sendUnknownMsg(String title, String msg, Throwable e) {
        try {
            String mdcId = MDCUtils.get();
            MsgSendConfig.getInstance().getPoolTaskExecutor().execute(() -> {
                MDCUtils.put(mdcId);
                ApiResponse<?> result = DingUtils.groupNotice(title + "\r\n" + buildMsg(msg, e, true).toString(), null);
                log.info("sendUnknownMsg end, result:{}", result);
            });
            return true;
        } catch (Exception ex) {
            LOG.error("sendUnknownMsg error:{}", ex.getMessage());
            return false;
        }
    }


    private static StringBuilder buildMsg(String msg, Boolean isShotMsg) {
        String line = isShotMsg ? MSG_LINE : HTML_LINE;

        StringBuilder sb = new StringBuilder();
        sb.append("application: [").append(MsgSendConfig.getInstance().getApplicationName()).append(" - ").append(MsgSendConfig.getInstance().getServerPort()).append(" - ").append(MsgSendConfig.getInstance().getProfilesActive()).append("]").append(line);
        sb.append("serverIp: [").append(IpUtils.getLocalNetWorkV4Ips()).append(" ; ").append(IpUtils.getLocalUserNames()).append("]").append(line);
        if (StringUtils.isNotEmpty(MDCUtils.get())) {
            sb.append("mdc-id: [").append(MDCUtils.get()).append("]").append(line);
        }

        sb.append("time: [").append(DateUtil.format(new Date(), DatePattern.NORM_DATETIME_MS_PATTERN)).append("]").append(line);
        sb.append("MSG: [").append(msg).append("]").append(line);
        return sb;
    }

    private static StringBuilder buildMsg(String msg, Throwable e, Boolean isShotMsg) {
        String line = isShotMsg ? MSG_LINE : HTML_LINE;

        String eMsg = (isShotMsg ? ExceptionUtil.getStackTraceAsStringLimit(e) : ExceptionUtil.getStackTraceAsString(e)).replace(getLineSeparator(), line);
        StringBuilder sb = buildMsg(msg, isShotMsg);
        sb.append("Exception:").append(line).append("[").append(eMsg).append("]").append(line);
        return sb;
    }

    private static String getLineSeparator() {
        if (LINE_SEPARATOR != null) {
            return LINE_SEPARATOR;
        }
        LINE_SEPARATOR = System.getProperty("line.separator");
        if (LINE_SEPARATOR == null) {
            LINE_SEPARATOR = "\r";
        }
        return LINE_SEPARATOR;
    }

}
